package com.yn.iotxiao.controller;

import com.alibaba.fastjson.JSONObject;
import com.yn.iotxiao.Utils.ExcelHelp;
import com.yn.iotxiao.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/excel")
@ResponseResult
public class ExcelController {

    @PostMapping
    public Object getExceData(@RequestParam("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
//        POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
        Workbook workbook = new XSSFWorkbook(inputStream);
        //HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);

        int rowCount = 0;
        List<String> keys = new ArrayList<>();
        List<JSONObject> list = new ArrayList<>();
        for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (rowCount == 0) {
                for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
                    log.info("j:" + j + ",key:" + row.getCell(j).getStringCellValue());
                    keys.add(row.getCell(j).getStringCellValue());
                }
            } else {
                JSONObject jObject = new JSONObject();
//                Map<String,String> hashMap = new HashMap<>();
                for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
//                    keys.add(row.getCell(j).getStringCellValue());
                    jObject.put(keys.get(j), ExcelHelp.getValue(row.getCell(j)));
//                    hashMap.put(keys.get(j), ExcelHelp.getValue(row.getCell(i)));
                }
                list.add(jObject);
            }
            rowCount++;
        }

        return list;
    }
}
